﻿namespace Admin.NET.Application.Service;

/// <summary>
/// 系统配置表
/// </summary>
[ApiDescriptionSettings(KeepName = true)]
public class BasConfigService : IDynamicApiController
{
    private readonly SqlSugarRepository<BasConfig> _rep;
    private readonly SysCacheService _sysCacheService;

    public BasConfigService(SqlSugarRepository<BasConfig> rep, SysCacheService sysCacheService)
    {
        _rep = rep;
        _sysCacheService = sysCacheService;
    }



    /// <summary>
    /// 获取列表, 用于基础资料查看
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public async Task<SqlSugarPagedList<BasConfigOutput>> Page(BaseKeywordPageInput input)
    {
        return await _rep.Queryable
           .WhereIF(input.Keyword.HasValue(), it => it.title.Contains(input.Keyword))
           .OrderBy(it => new { it.category1, it.category2, it.code })
           .Select<BasConfigOutput>()
           .ToPagedListAsync(input.Page, input.PageSize);
    }


    /// <summary>
    /// 全部 , 用于前端缓存
    /// </summary>
    public async Task<List<BasConfigAllOutput>> All()
    {
        var cacheData = _sysCacheService.Get<List<BasConfigAllOutput>>(CacheConst.BasConfigList);
        if (cacheData == null || cacheData.Count() <= 0)
        {
            var list = await _rep.Queryable
            .Select<BasConfigAllOutput>()
            .ToListAsync();

            cacheData = list;
            _sysCacheService.Set(CacheConst.BasConfigList, cacheData);
        }

        return cacheData;
    }


    /// <summary>
    /// 更新参数值
    /// </summary>
    public bool Update(BasConfigInput input)
    {
        //刷新缓存
        _sysCacheService.Remove(CacheConst.BasConfigList);

        var eff = _rep.AsUpdateable(new BasConfig() { code = input.code, val = input.val, remark = input.remark })
                      .UpdateColumns(it => new { it.val, it.remark, it.UpdateTime, it.UpdateUserId, it.UpdateUserName }).ExecuteCommand();

        return eff > 0;
    }
}
